package com.yugao.fintech.antelope.mps.core.sender;

import com.alibaba.fastjson2.JSON;
import com.yugao.fintech.antelope.infra.InfraApi;
import com.yugao.fintech.antelope.infra.module.file.model.rqrs.MediaMaterialResp;
import com.yugao.fintech.antelope.mps.api.constatnts.ChannelCodeEnum;
import com.yugao.fintech.antelope.mps.api.constatnts.ChannelTypeEnum;
import com.yugao.fintech.antelope.mps.api.constatnts.MsgPushStatus;
import com.yugao.fintech.antelope.mps.api.model.content.MsgContent;
import com.yugao.fintech.antelope.mps.api.model.content.template.TemplateVarData;
import com.yugao.fintech.antelope.mps.api.model.rqrs.SitePushReq;
import com.yugao.fintech.antelope.mps.core.PushTaskContext;
import com.yugao.fintech.antelope.mps.core.channel.websocket.PcChannelClient;
import com.yugao.fintech.antelope.mps.core.parser.PcTemplateParser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 推送到pc端
 */
@Slf4j
@Service
public class PcSender implements MsgSender {
    @Autowired
    private InfraApi infraApi;

    @Override
    public void sendMessage(PushTaskContext context) {
        context.setChannelCode(ChannelCodeEnum.PC);

        MsgContent msgContent = (MsgContent) context.getMsgContent();
        PcTemplateParser template = (PcTemplateParser) context.getTplConfig();
        Map<String, TemplateVarData> varDataMap = template.getVarData().values().stream()
                .collect(Collectors.toMap(TemplateVarData::getKey, Function.identity()));

        SitePushReq req = new SitePushReq();
        req.setContent(template.getRenderContent()).setBizType(msgContent.getBizType())
                .setTitle(msgContent.getTitle()).setPageUrl(msgContent.getPageUrl()).setVarData(varDataMap);
        req.setTaskCode(msgContent.getTaskCode());
        req.setUserId(msgContent.getToUser());
        req.setLoginId(msgContent.getLoginId());

        if (Objects.nonNull(template.getMediaId())) {
            MediaMaterialResp material = infraApi.getMediaMaterial(template.getMediaId());
            if (log.isDebugEnabled()) {
                log.debug("push pc material: {}", JSON.toJSONString(material));
            }
            if (Objects.nonNull(material)) {
                req.setMediaType(material.getType());
                req.setMediaUrl(material.getUrl());
            }
        }
        log.info("push pc req: {}", JSON.toJSONString(req));
        PcChannelClient.sendMsg(req);
        context.setPushResult("success");
        context.setPushStatus(MsgPushStatus.SUCCESS);
    }

    @Override
    public ChannelTypeEnum channelType() {
        return ChannelTypeEnum.PC;
    }
}
